package cn.ahaoweb.drule.core.compile.provide.hepler;

import cn.ahaoweb.drule.core.compile.provide.ObjectTree;
import cn.ahaoweb.drule.core.compile.structure.DruleBlock;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ahao
 * @datetime 2025/6/4 13:49
 * @description 对象字段定位器
 */
public class FieldUsedLocator {

    // 默认的字段匹配器
    private static final SimpleFieldMatcher SIMPLE_FIELD_MATCHER = new SimpleFieldMatcher();

    public static List<MatchedField> simpleLocate(List<DruleBlock> druleBlockList, List<ObjectTree.Node> nodes) {

        return locate(druleBlockList, nodes, SIMPLE_FIELD_MATCHER);
    }


    /**
     * 根据给定的规则块列表和字段节点列表，关联字段出现过的规则块列表
     *
     * @param druleBlockList 规则块列表
     * @param nodes          字段节点列表
     * @param fieldMatcher   字段匹配器
     * @return 匹配结果列表，每个元素包含字段及其对应的规则块列表
     */
    public static List<MatchedField> locate(List<DruleBlock> druleBlockList, List<ObjectTree.Node> nodes, FieldMatcher fieldMatcher) {
        List<MatchedField> matchedFields = new ArrayList<>();
        if (nodes != null && nodes.size() > 0
                && druleBlockList != null && druleBlockList.size() > 0) {
            for (ObjectTree.Node node : nodes) {
                MatchedField matchedField = new MatchedField(node);
                for (DruleBlock druleBlock : druleBlockList) {
                    // 匹配
                    List<DruleBlock.Condition> conditions = fieldMatcher.matchWhen(druleBlock.getWhen(), node);
                    if (conditions != null && conditions.size() > 0) {
                        matchedField.setMatched(true);
                        matchedField.addCondition(druleBlock,conditions);
                    }
                    List<DruleBlock.Action> actions = fieldMatcher.matchThen(druleBlock.getThen(), node);
                    if (actions != null && actions.size() > 0) {
                        matchedField.setMatched(true);
                        matchedField.addAction(druleBlock,actions);
                    }
                }
                matchedFields.add(matchedField);
            }
        }
        return matchedFields;
    }

}
